package com.shirostudy.config;

import com.shirostudy.pojo.RbacManager;
import com.shirostudy.service.RbacManagerService;
import com.shirostudy.service.impl.RbacManagerServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @BelongsProject: java-85-course-code
 * @BelongsPackage: com.shirostudy.config
 * @Author: LiTongMiao
 * @Date: 2022/2/23 15:20
 * @Description: TODO
 */
//自定义UserRealm
//用户认证，权限操作的地方
public class UserRealm extends AuthorizingRealm {

    @Autowired(required = false)
    RbacManagerServiceImpl rbacManagerService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了=>授权AuthorizationInfo");
        //SimpleAuthorizationInfo 给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // info.addStringPermission(“aaa:add”);//设置权限

        //获取当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        RbacManager currentuser = (RbacManager) subject.getPrincipal();//拿到User对象

        //info.addStringPermission(currentuser.getPerms());//从数据库拿到权限,这里的数据库表中应该是有perems字段存储限权，我的数据库中没有才报错


        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证AuthenticationInfo");


        UsernamePasswordToken userToken=(UsernamePasswordToken) token;
       //连接真实的数据库
        RbacManager user= rbacManagerService.findRbacManagerByName(userToken.getUsername());

        if(user == null){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
